package com.xiaozhengkeji.mcverifyplus.utils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class MailUtils {
    /**
     * 发送邮件
     *
     * @param subject       邮件主题
     * @param content       邮件内容（支持HTML）
     * @param toEmailAddres 收件人
     * @throws Exception
     * @author Monk
     * @date 2019年5月22日 下午6:27:27
     */
    public static void sendMail(String subject, String content, String toEmailAddres) throws Exception {
        String host = "mail.xiaozhengkeji.com";        //邮箱服务器地址
        String port = "25";                        //发送邮件的端口
        String auth = "true";                     //是否需要进行身份验证,视调用的邮箱而定，比方说QQ邮箱就需要，否则就会发送失败
        String protocol = "smtp";                  //传输协议
        String mailFrom = "mcverifyplus@xiaozhengkeji.com";   //发件人邮箱
        String personalName = "mcverifyplus";         //发件人邮箱别名
        String username = "mcverifyplus@xiaozhengkeji.com";   //发件人邮箱用户名
        String password = "McverifyPlus0";               //发件人邮箱密码
        String mailDebug = "true";                //是否开启debug
        String contentType = null;                 //邮件正文类型
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", auth == null ? "true" : auth);
        props.put("mail.transport.protocol", protocol == null ? "smtp" : protocol);
        props.put("mail.smtp.port", port == null ? "25" : port);
        props.put("mail.debug", mailDebug == null ? "false" : mailDebug);
        Session mailSession = Session.getInstance(props);
        // 设置session,和邮件服务器进行通讯。
        MimeMessage message = new MimeMessage(mailSession);
        // 设置邮件主题
        message.setSubject(subject);
        // 设置邮件正文
        message.setContent(content, contentType == null ? "text/html;charset=UTF-8" : contentType);
        // 设置邮件发送日期
        message.setSentDate(new Date());
        InternetAddress address = new InternetAddress(mailFrom, personalName);
        // 设置邮件发送者的地址
        message.setFrom(address);
        // 设置邮件接收方的地址
        message.setRecipients(Message.RecipientType.TO, toEmailAddres);
        Transport transport = null;
        transport = mailSession.getTransport();
        message.saveChanges();
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
